package com.example.springboot3demo.config;

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        OpenAPI openAPI = new OpenAPI()
                .info(new Info().title("Springboot3demo 后台服务API接口文档")
                        .description("restful 风格接口")
                        .version("v0.0.1")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("Springboot3demo Documentation")
                        .url("https://gitee.com/l_o_a_n/springboot3demo.git"));

        return openAPI;
    }

    @Bean
    public OperationCustomizer globalHeaderCustomizer() {
        //遍历所有操作(即接口)
        return (Operation operation, HandlerMethod handlerMethod) -> {
            //设置全局请求头参数
            if (!StringUtils.equals("login", operation.getOperationId())) {
                setHeader(operation);
            }
            return operation;
        };
    }

    //设置全局请求头
    private void setHeader(Operation operation){
        Parameter tokenParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name(HttpHeaders.AUTHORIZATION)
                .description("token")
                .required(true);
        operation.addParametersItem(tokenParam);
    }

}